package com.beerq.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.alibaba.fastjson.JSONObject;
import com.beerq.R;
import com.beerq.util.AppConfig;
import com.beerq.util.BasicHttp;
import com.beerq.util.Constants;
import com.beerq.view.me.LoginActivity;
import com.beerq.view.purchase.PostEvaluateActivity;
import com.beerq.view_manager.AlipayManamger;
import com.beerq.view_manager.PayManager;
import com.beerq.view_manager.WeChatManager;

import okhttp3.RequestBody;

/**
 * 作者：minj on 2017/9/23 13:19
 * 商品信息的js和android的交互累
 */
public class ProductJsManager {

    private Context mContext;

    private View mLinBackToTop;

    private  WebView mWebView;

    public ProductJsManager(Context c, WebView webView) {
        mContext = c;
        mWebView = webView;
    }

    public void setLin_back_to_top(View lin_back_to_top) {
        mLinBackToTop = lin_back_to_top;

    }

    /***
     * 进入到商品的详情页
     * @param pId 商品的ID
     */
    @JavascriptInterface
    public void setProductId(String pId) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        String url = Constants.domain + "#/detail?DetailId=" + pId;
        intent.putExtra("barType","1");
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }

    /***
     * 进入秒杀商品的详情页的详情页
     * @param pId 商品的ID
     */
    @JavascriptInterface
    public void setSaleProductId(String pId) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("barType","1");
        String url = Constants.domain + "#/detail?DetailId=" + pId;
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }

    /***
     * 提交订单 javascript通过这个接口把订单号和金额传给android
     * @param orderNo 订单号
//     * @param amount 金额
     * @param type 0微信 1支付宝
     */
    @JavascriptInterface
    public void orderpay(final String orderNo, int type) {
        if (type == 0) {
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("OrderNum", orderNo);
            //jsonObject.put("TotalAmout", amount);
            RequestBody requestBodyPost = AppConfig.getBasicRequestBody(mContext).add("Args", jsonObject.toJSONString()).build();
            BasicHttp.postExec(mContext, Constants.server_domain + "pay/GetPrePay", requestBodyPost, new BasicHttp.IMyCallBack() {
                @Override
                public void onResponse(String resonseData) {
                    PayManager.doStartWechatPay(mContext, JSONObject.parseObject(resonseData).getJSONObject("Result"));
                }

                @Override
                public void onFailure(String resonseData) {

                }
            });
        } else if (type == 1) {
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("HaveOrderDetail", false);
            jsonObject.put("OrderCode", orderNo);
            RequestBody requestBodyPost = AppConfig.getBasicRequestBody(mContext).add("Args", jsonObject.toJSONString()).build();
            BasicHttp.postExec(mContext, "http://106.14.140.112:8011/api/morder/OrdGetOne", requestBodyPost, new BasicHttp.IMyCallBack() {
                @Override
                public void onResponse(String resonseData) {

                    new AlipayManamger(mContext).pay(orderNo,JSONObject.parseObject(resonseData).getJSONObject("Result").getString("PayAmount"));
//                    PayManager.doStartWechatPay(mContext, JSONObject.parseObject(resonseData).getJSONObject("Result"));
                }

                @Override
                public void onFailure(String resonseData) {

                }
            });



//
        }
}


    /***
     * 进入到购物车页面
     */
    @JavascriptInterface
    public void setShopCart() {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("barType","1");
        intent.putExtra("url", Constants.domain + "#/shopcar?fromPage=goods");
        mContext.startActivity(intent);
    }

    /***
     * 进入到客服界面
     */
    @JavascriptInterface
    public void openNews() {
        Intent intent = new Intent(mContext, ServicesActivity.class);
        mContext.startActivity(intent);
    }


    /***
     * 控制底部的 回调顶部按钮的 显示和隐藏
     * @param flag 1是显示 0是隐藏
     * @param smallType 代表 商品 国家什么的
     * @param typee 1代表好啤酒 2代表啤酒志
     */
    @JavascriptInterface
    public void webScroll(final int flag, int smallType, int typee) {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mLinBackToTop!=null){
                    if (flag == 1) {
                        mLinBackToTop.setVisibility(View.VISIBLE);
                    } else {
                        mLinBackToTop.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    /***
     * 判断当前页面是否显示 返回到顶部按钮
     * 返回的参数通过 在注册的WebChromeClient中的onJsAlert中返回
     */
    public static void isShowBackToTop(WebView webView) {
        webView.loadUrl("javascript:webviewGetScroll()");
    }


    /***
     * 添加用户的浏览器缓存信息
     * @param webView
     * @param userId
     */
    public static void setUserInfo(WebView webView, int userId) {
        if(webView==null)return;
        webView.loadUrl("javascript:storageUserId(" + userId + ")");
    }

    /***
     * 清空用户的浏览器缓存信息
     * @param webView
     */
    public static void clearUserInfo(WebView webView) {
        webView.loadUrl("javascript:clearStorage()");
    }




    /***
     * 调用商品评价
     * @param itemId 商品ID
     * @param imgUrl 商品图片logo
     */
    @JavascriptInterface
        public  void goAssess(int itemId,String imgUrl,String code) {
        Intent intent=new Intent(mContext, PostEvaluateActivity.class);
        intent.putExtra("itemId",itemId);
        intent.putExtra("imgUrl",imgUrl);
        intent.putExtra("code",code);
        mContext.startActivity(intent);

    }

    /***
     * 进入到啤酒志的详情页
     * @param contentId
     */
    @JavascriptInterface
    public void setContentId(String contentId) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        String url = Constants.domain + "piqizhi/#/content?contentId=" + contentId;
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }


    @JavascriptInterface
    public void goToBack(int typee) {
        ((BaseActivity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((BaseActivity) mContext).finish();
            }
        });
    }

    @JavascriptInterface
    public void goToBack() {
        ((BaseActivity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    ((BaseActivity) mContext).finish();
                }
            }
        });
    }

    @JavascriptInterface
    public void goLogin() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }


    //品牌绑定
    @JavascriptInterface
    public void goGoodsBrand(String bid) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        String url = Constants.domain + "#/goods?brandId=" + bid;
        intent.putExtra("barType","1");
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }


    //推荐进入到活动页面
    @JavascriptInterface
    public void goActivity() {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        String url = Constants.domain + "#/activity";
        intent.putExtra("barType","1");
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }



    //关闭活动页面
    @JavascriptInterface
    public void closeactivity() {
//        Intent intent = new Intent(mContext, WebViewActivity.class);
//        String url = Constants.domain + "#/activity";
//        intent.putExtra("barType","1");
//        intent.putExtra("url", url);
//        mContext.startActivity(intent);

        ((Activity)mContext).finish();

    }



    //关闭活动页面
    @JavascriptInterface
    public void actGoDetail(String itemid) {
        Intent intent = new Intent(mContext, WebViewActivity.class);
        String url = Constants.domain + "#/detail?DetailId="+itemid;
        intent.putExtra("barType","1");
        intent.putExtra("url", url);
        mContext.startActivity(intent);
    }

    /***
     * 分享
     * @param title
     * @param url
     */
    @JavascriptInterface
    public void openShare(String title,String url) {
//        WeChatManager.wechatShare();
        makeShareShow(title,url);
    }


    private void makeShareShow( final String title,final String url){
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_popwindow_view, null);
        final Dialog dialog = new Dialog(mContext, R.style.common_dialog);
        dialog.setContentView(view);
//        dialog.getWindow().setWindowAnimations(R.style.MyDialogAnimationStyle);
        dialog.show();

        // 设置相关位置，一定要在 show()之后
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);

        view.findViewById(R.id.lin_share_wechat_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WeChatManager.wechatShare(mContext,1,title,url);
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.lin_share_wechat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WeChatManager.wechatShare(mContext,0,title,url);
                dialog.dismiss();
            }
        });

    }

}



